package com.cloud.shopping.cart.service.impl;

import com.cloud.shopping.cart.mapper.CartMapper;
import com.cloud.shopping.cart.model.Cart;
import com.cloud.shopping.cart.service.CartService;
import com.cloud.shopping.goods.feign.SkuFeign;
import com.cloud.shopping.goods.model.Sku;
import com.cloud.shopping.tool.RespResult;
import com.google.common.collect.Lists;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author John.zhang
 * @version Id: CartServiceImpl, v 1.0 2021/1/3 19:37 ZhiYong Exp $
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private SkuFeign skuFeign;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public List<Cart> list(List<String> ids) {
        if (ids != null && ids.size() > 0) {
            //根据ID集合查询
            Iterable<Cart> carts = cartMapper.findAllById(ids);
            return Lists.newArrayList(carts);
        }
        return null;
    }

    @Override
    public List<Cart> list(String userName) {
        //条件构建
        Cart cart = new Cart();
        cart.setUserName(userName);
        return cartMapper.findAll(Example.of(cart), Sort.by("_id"));
    }

    @Override
    public void add(String id, String userName, Integer num) {
        //ID 不能冲突
        //1)删除当前ID对应的商品之前的购物车记录
        cartMapper.deleteById(userName + id);

        if (num > 0) {
            //2）根据ID查询Sku详情
            RespResult<Sku> skuResp = skuFeign.one(id);

            //3)将当前ID商品对应的数据加入购物车（存入到MongoDB）
            Sku sku = skuResp.getData();
            Cart cart = new Cart(userName + id, userName, sku.getName(), sku.getPrice(), sku.getImage(), id, num);
            cartMapper.save(cart);
        }
    }

    @Override
    public void delete(List<String> ids) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").in(ids)), Cart.class);
    }
}
